# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Jürgen Pfeifer <juergen@familiepfeifer.de>

_realname=OpenBLAS
pkgbase=mingw-w64-${_realname}-git
pkgname="${MINGW_PACKAGE_PREFIX}-openblas-git"
pkgrel=1
pkgver=r2017.bd06b24
pkgdesc="An optimized BLAS library based on GotoBLAS2 1.13 BSD, providing optimized blas, lapack, and cblas (mingw-w64)"
provides=("${MINGW_PACKAGE_PREFIX}-${_realname}")
arch=('any')
url="http://www.openblas.net/"
license=('BSD')
provides=("${MINGW_PACKAGE_PREFIX}-${_realname}"
          "${MINGW_PACKAGE_PREFIX}-openblas")
conflicts=("${MINGW_PACKAGE_PREFIX}-openblas")
replaces=("${MINGW_PACKAGE_PREFIX}-${_realname}"
          "${MINGW_PACKAGE_PREFIX}-${_realname}-git")
options=('strip' 'staticlibs')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-gcc-libgfortran"
         "${MINGW_PACKAGE_PREFIX}-libwinpthread")
makedepends=("git"
             "${MINGW_PACKAGE_PREFIX}-gcc"
             "${MINGW_PACKAGE_PREFIX}-gcc-fortran")
source=("${_realname}"::"git+https://github.com/xianyi/${_realname}")
sha256sums=('SKIP')

pkgver() {
  cd "$srcdir/$_realname"
  printf "r%s.%s" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
}

build() {
  mkdir -p ${srcdir}/build-${CARCH} && cd ${srcdir}/build-${CARCH}
  git clone ${srcdir}/${_realname} .
  make LIBNAME=libopenblasp.a CC=gcc FC=gfortran DYNAMIC_ARCH=1 \
       OPENBLAS_INCLUDE_DIR=${MINGW_PREFIX}/include/${_realname}
}

package() {
  cd "${srcdir}"/build-${CARCH}

  if [ -f libopenblas.dll ]; then
    if [ -f exports/libopenblas.def ]; then
      dlltool -D libopenblas.dll -d exports/libopenblas.def -l libopenblas.dll.a
    else
      echo "Cannot build export library" >&2
      exit 1
    fi
  else
    echo "DLL not found" >&2
    exit 1
  fi
  mkdir -p "${pkgdir}${MINGW_PREFIX}/bin"
  mkdir -p "${pkgdir}${MINGW_PREFIX}/lib"

  make LIBNAME=libopenblasp.a \
       DESTDIR="${pkgdir}" PREFIX="${MINGW_PREFIX}"  \
       OPENBLAS_INCLUDE_DIR=${MINGW_PREFIX}/include/${_realname} \
       install

  if [ -f libopenblas.dll ]; then
    cp -f libopenblas.dll "${pkgdir}${MINGW_PREFIX}/bin/"
  else
    echo "DLL not found" >&2
    exit 1
  fi

  if [ -f libopenblas.dll.a ]; then
    cp -f libopenblas.dll.a "${pkgdir}${MINGW_PREFIX}/lib/"
  else
    echo "Export library not found" >&2
    exit 1
  fi

  if [ -f libopenblasp.a ]; then
    rm -f "${pkgdir}$MINGW_PREFIX/lib/libopenblasp.a"
    rm -f "${pkgdir}$MINGW_PREFIX/lib/libopenblas.a"
    cp -f libopenblasp.a "${pkgdir}${MINGW_PREFIX}/lib/libopenblas.a"
  else
    echo "Static library not found" >&2
    exit 1
  fi

  # Copy Licencse
  mkdir -p ${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}
  cp -f "${srcdir}"/build-${CARCH}/LICENSE \
    ${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}
  cp -f "${srcdir}"/build-${CARCH}/lapack-netlib/LICENSE \
    ${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE-lapack
}
